<template>
	<view class="cart-container">
		<!-- 购物车列表 -->
		<view class="cart-list">
			<view class="cart-item" v-for="(item, i) in cartList" :key="i">
				<view class="item-left">
					<image :src="item.goods.goods_image" mode="widthFix" />
				</view>
				<view class="item-right">
					<view class="goods-name">
						{{item.goods.goods_name}}
					</view>
					<view class="goods-price">
						{{item.goods.goods_price_max}}
					</view>
					<view class="goods-num">
						{{item.goods_num}}
					</view>
				</view>
			</view>
		</view>

		<!-- 商品总价 -->
		<view class="total-price">
			商品总价：{{totalPrice}}
		</view>

		<!-- 商品总数 -->
		<view class="total-num">
			商品总数：{{totalNum}}
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request'
	export default {
		data() {
			return {
				// 购物车列表
				cartList: [],
			};
		},
		onLoad() {
			this.getCartList()
		},
		computed: {
			// 商品总价
			totalPrice() {
				const totalPrice = this.cartList.reduce((acc, current) => {
					return acc + (current.goods_num * current.goods.goods_price_max)
				}, 0)
				console.log('totalPrice', totalPrice)
				return totalPrice
			},
			// 商品总数
			totalNum() {
				const totalNum = this.cartList.reduce((acc, current) => {
					return acc + current.goods_num
				}, 0)
				console.log('totalNum', totalNum)
				return totalNum
			}
		},
		watch: {
			totalNum: (newTotalNum) => {
				console.log('商品总数发生变化', newTotalNum)
				uni.setTabBarBadge({
					index: 2,
					text: `${newTotalNum}`
				})
			}
		},
		methods: {
			// 获取购物车列表
			async getCartList() {
				try {
					const cartPageRes = await request.get('cart/list')
					console.log('购物车列表相应', cartPageRes)
					// 设置页面数据
					this.cartList = cartPageRes.data.list
					console.log('购物车列表', this.cartList)
				} catch (e) {
					console.log('获取购物车数据异常', e)
				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.cart-container {
		.cart-list {
			.cart-item {
				display: flex;

				.item-left {
					flex: 2;

					image {
						width: 100%;
					}
				}

				.item-right {
					flex: 3;
				}
			}
		}
	}
</style>